import React, { useEffect, useState } from "react";

function Function() {
  console.log("函数被执行");

  const initialTimer = 10;

  const [timer, setTimer] = useState(initialTimer);
  const [hello, setHello] = useState('hi!');



  useEffect(() => {
    console.log('Effect 被执行');
  //   setInterval(() => {
  //     console.log('Timer + 1');
  //     setTimer(oldTimer => oldTimer + 1);
  //     // BAD
  //     // setTimer(timer + 1); // 闭包变量, 始终是初始值
  //   }, 5000);
  // }, []);

  const timer = setTimeout(() => {
    setTimer(timer + 1);
    setHello(hello + ' hi!');
  }, 1000);

  return() => {
    console.log('清理')
    clearTimeout(timer);
  }
}, [timer,hello]);
  


  const onX2 = () => {
    setTimer(timer * 2);
  };

  const onMinus1 = () =>{
    setTimer(timer - 1);
  };

  const onReset = () => {
    setTimer(initialTimer);
  }



  return (
    <>
    
       <button onClick={onX2}>X2</button>
       <button onClick={onMinus1}>-1</button>
       <button onClick={onReset}>onReset</button>
       <h3>{hello}</h3>

      <div>第一个函数组件 {timer}</div>
    </>
  );
}

export default Function;
